package it.poste.il.compensatore.servlets;

import it.poste.il.compensatore.control.Integration;
import it.poste.il.compensatore.control.impl.IntegrationImpl;

import java.io.BufferedReader;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

//import org.springframework.web.context.WebApplicationContext;
//import org.springframework.web.context.support.WebApplicationContextUtils;

public class HttpReceiver extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static Logger logger = Logger.getLogger("HttpReceiver");
	

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		//WebApplicationContext springContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext());    
		//Integration integrationImpl= (Integration) springContext.getBean("IntegrationImpl");
		
		Integration engine = IntegrationImpl.getInstance();
		//Integration engine = new IntegrationImpl();
		logger.debug("POST Partito!");
		
		
		
		StringBuffer jb = new StringBuffer();
		String line = null;
		try {
			BufferedReader reader = request.getReader();
		    while ((line = reader.readLine()) != null)
		    	jb.append(line);
		} catch (Exception e) {
			e.printStackTrace();
		}
		String soapRequest = jb.toString();
		logger.debug("Messaggio: " + soapRequest);

		String soapAction = request.getHeader("SOAPAction");
		logger.debug("SOAP Action: " + soapAction);
		
		logger.debug(" --- Chiamata all'IntegrationImpl --- ");

		String result = null;
		try {
			result = engine.syncMsg(soapRequest);
		} catch (Exception e) {
			//TODO Gestire eccezione ...
			e.printStackTrace();
		}
		// Send SDP response
		ServletOutputStream respStream = response.getOutputStream();
		respStream.write(result.getBytes());
		respStream.close();
	}

}
